$(function(){
    /*各组件根据打开窗口大小  初始化响应一次*/
    baseOnWindowSizeToChange();

    /*窗口宽度高度发生变化时，触发各组件响应函数*/
    $(window).resize(
        function() {
            baseOnWindowSizeToChange();
        }
    );

    /* 打开网易云播放器 */
    let isopen = 0;
    $("#openMusic").click(function (){
        if(isopen === 0) {
            $(".netease_Player").css("display", "block");
            isopen = 1;
        } else {
            $(".netease_Player").css("display", "none");
            isopen = 0;
        }
    });

    //从缓存中获取数据（在登录成功后会将当前用户和用户令牌放入缓存中）
    let user = JSON.parse(window.sessionStorage.getItem("user"));
    const token = window.sessionStorage.getItem("token");
    if(user == null || token == null){
        alert("请先登录");
        window.location.href = "../html/welcome.html";
    }

    $("#username").html(user.username);

    let studyBtn = document.getElementById("study");
    let videoBtn = document.getElementById("video");
    studyBtn.onclick = function (){
        spop({
            template: "个人博客模块尚未完成",
            position  : 'top-center',
            group: "submit-satus",
            style: "failed",
            autoclose: 2000
        });
    }
    videoBtn.onclick = function (){
        spop({
            template: "教学视频模块尚未完成",
            position  : 'top-center',
            group: "submit-satus",
            style: "failed",
            autoclose: 2000
        });
    }

    //给退出按钮添加点击事件
    let logoutBtn = document.getElementById("logoutBtn");
    logoutBtn.onclick = function (){
        logoutAjax(user.username);
    }

    //点击个人中心按钮时查询当前的用户信息
    $("#personalInfoBtn").click(function (){
        //再次获取缓存中的用户数据
        user = JSON.parse(window.sessionStorage.getItem("user"));
        //修改按钮文字
        $("#updatePersonalInfoBtn").val("修改");
        //更换为展示个人信息的样式
        changeToShow();
        //赋值
        $("#personalUsername").text(user.username != null ? user.username : "尚未填写");
        $("#personalPassword").text(user.password != null ? user.password : "尚未填写");
        $("#personalSex").text(user.sex != null ? user.sex : "尚未填写");
        $("#personalBirthday").text(user.birthday != null ? user.birthday : "尚未填写");
        $("#personalPhone").text(user.phone != null ? user.phone : "尚未填写");
        $("#personalEmail").text(user.email != null ? user.email : "尚未填写");
    });

    //修改前的用户名
    let beforeUsername = null;
    //为修改按钮和保存按钮添加点击事件
    $("#updatePersonalInfoBtn").click(function (){
        if($("#updatePersonalInfoBtn").val() === "修改"){
            //再次获取缓存中的用户数据
            user = JSON.parse(window.sessionStorage.getItem("user"));
            //更换为修改个人信息的样式
            changeToUpdate();
            //赋值
            beforeUsername = null;
            beforeUsername = user.username;
            $("#personalUsername").val(user.username);
            $("#personalPassword").val(user.password);
            if(user.sex != null){
                $("#personalSex").val(user.sex);
            }
            $("#personalBirthday").val(user.birthday)
            $("#personalPhone").val(user.phone);
            $("#personalEmail").val(user.email);
            //修改按钮文字
            $("#updatePersonalInfoBtn").val("保存");
        }else if($("#updatePersonalInfoBtn").val() === "保存"){
            //获取修改后的数据，创建用户实体类
            const updateUser = new User(user.userId,$("#personalUsername").val(),$("#personalPassword").val(),$("#personalSex").val(),
                                    $("#personalBirthday").val(),$("#personalPhone").val(),$("#personalEmail").val());
            //修改用户信息ajax
            if($("#personalUsername").val() !== beforeUsername){
                updateUserAjax(token,updateUser,true);
            }else {
                updateUserAjax(token,updateUser,false);
            }
        }
    });

    //关闭页面时调用logout方法，退出当前登录用户
    $(window).unload(function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            url :"http://localhost:2082/logout?username=" + user.username
        })
    });

});

/*窗口宽度高度发生变化时，各组件应当的响应*/
function baseOnWindowSizeToChange() {
    //获取底部单个选项宽度大小并赋给上拉表单宽度
    let dropdownWidth = $(".bottomSelect").width();
    $(".dropdownSelect").css("width", dropdownWidth);

}

//退出登录ajax
function logoutAjax(username){
    $.ajax({
        type:"POST",
        contentType:"application/json",
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        url :"http://localhost:2082/logout?username=" + username,
        success : function(data) {
            let result = JSON.stringify(data);
            result = eval("("+result+")");
            let code = result.code;
            let msg = result.msg;
            //操作成功
            if(code == 200){
                spop({
                    template: msg,
                    position  : 'top-center',
                    group: "submit-satus",
                    style: "success",
                    autoclose: 2000
                });
                window.setTimeout(function(){
                    location.href = "welcome.html";
                },2000);
            }
            //操作失败
            if(code == 500){
                $('#register').modal('hide');
                spop({
                    template: msg,
                    position  : 'top-center',
                    group: "submit-satus",
                    style: "fail",
                    autoclose: 2000
                });
            }
        }
    })
}

//用户实体类
function User(userId,username,password,sex,birthday,phone,email) {
    this.userId = userId;
    this.username = username;
    this.password = password;
    this.sex = sex;
    this.birthday = birthday;
    this.phone = phone;
    this.email = email;
}

//修改用户信息ajax
function updateUserAjax(token,updateUser,isUpdateUsername){
    $.ajax({
        type: "PATCH",
        contentType: "application/json",
        headers: {
            "token":token
        },
        data: JSON.stringify(updateUser),
        url: "http://localhost:2082/user?isUpdateUsername=" + isUpdateUsername,
        success: function(data,status,xhr) {
            //若用户认证过期，后端返回的响应头中会有一个token字段，值为overdue
            const responseToken = xhr.getResponseHeader("token");
            if(responseToken == "overdue"){
                alert("用户认证已过期，请重新登录");
                window.location.href = "../html/welcome.html";
            }else {
                let result = JSON.stringify(data);
                result = eval("("+result+")");
                //操作成功
                if(result.code == 200){
                    //刷新缓存
                    window.sessionStorage.removeItem("user");
                    window.sessionStorage.setItem("user",JSON.stringify(updateUser));
                    //更换为展示个人信息的样式
                    changeToShow();
                    //赋值
                    $("#personalUsername").text(updateUser.username != null ? updateUser.username : "尚未填写");
                    $("#personalPassword").text(updateUser.password != null ? updateUser.password : "尚未填写");
                    $("#personalSex").text(updateUser.sex != null ? updateUser.sex : "尚未填写");
                    $("#personalBirthday").text(updateUser.birthday != null ? updateUser.birthday : "尚未填写");
                    $("#personalPhone").text(updateUser.phone != null ? updateUser.phone : "尚未填写");
                    $("#personalEmail").text(updateUser.email != null ? updateUser.email : "尚未填写");
                    //修改按钮文字
                    $("#updatePersonalInfoBtn").val("修改");
                    //修改用户名
                    $("#username").html(updateUser.username);
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "success",
                        autoclose: 2000
                    });
                }
                //操作失败
                else if(result.code == 500){
                    spop({
                        template: result.msg,
                        position  : 'top-center',
                        group: "submit-satus",
                        style: "fail",
                        autoclose: 2000
                    });
                }
            }
        }
    })
}

//展示个人信息的样式
function changeToShow(){
    $("#personalUsernameLabel").replaceWith("<label id=\"personalUsernameLabel\" for=\"personalUsername\">&nbsp;&nbsp;&nbsp;&nbsp;用户名:&nbsp;</label>");
    $("#personalPasswordLabel").replaceWith("<label id=\"personalPasswordLabel\" for=\"personalPassword\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;密码:&nbsp;</label>");
    $("#personalSexLabel").replaceWith("<label id=\"personalSexLabel\" for=\"personalSex\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;性别:&nbsp;</label>");
    $("#personalBirthdayLabel").replaceWith("<label id=\"personalBirthdayLabel\" for=\"personalBirthday\">出生日期:&nbsp;</label>");
    $("#personalPhoneLabel").replaceWith("<label id=\"personalPhoneLabel\" for=\"personalPhone\">联系方式:&nbsp;</label>");
    $("#personalEmailLabel").replaceWith("<label id=\"personalEmailLabel\" for=\"personalEmail\">电子邮箱:&nbsp;</label>");

    $("#personalUsername").replaceWith("<label id=\"personalUsername\"></label>");
    $("#personalPassword").replaceWith("<label id=\"personalPassword\"></label>");
    $("#personalSex").replaceWith("<label id=\"personalSex\"></label>");
    $("#personalBirthday").replaceWith("<label id=\"personalBirthday\"></label>");
    $("#personalPhone").replaceWith("<label id=\"personalPhone\"></label>");
    $("#personalEmail").replaceWith("<label id=\"personalEmail\"></label>");
}

//修改个人信息的样式
function changeToUpdate(){
    $("#personalUsernameLabel").replaceWith("<label id=\"personalUsernameLabel\" for=\"personalUsername\">用户名:</label>");
    $("#personalPasswordLabel").replaceWith("<label id=\"personalPasswordLabel\" for=\"personalPassword\">密码:</label>");
    $("#personalSexLabel").replaceWith("<label id=\"personalSexLabel\" for=\"personalSex\">性别:</label>");
    $("#personalBirthdayLabel").replaceWith("<label id=\"personalBirthdayLabel\" for=\"personalBirthday\">出生日期:</label>");
    $("#personalPhoneLabel").replaceWith("<label id=\"personalPhoneLabel\" for=\"personalPhone\">联系方式:</label>");
    $("#personalEmailLabel").replaceWith("<label id=\"personalEmailLabel\" for=\"personalEmail\">电子邮箱:</label>");

    $("#personalUsername").replaceWith("<input class=\"form-control\" type=\"\" id=\"personalUsername\">");
    $("#personalPassword").replaceWith("<input class=\"form-control\" type=\"\" id=\"personalPassword\">");
    $("#personalSex").replaceWith("<select id=\"personalSex\" class=\"form-control\">\n" +
        "                                                        <option value=\"\" hidden></option>\n" +
        "                                                        <option value=\"男\">男</option>\n" +
        "                                                        <option value=\"女\">女</option>\n" +
        "                                                    </select>");
    $("#personalBirthday").replaceWith("<input class=\"form-control\" type=\"date\" id=\"personalBirthday\">");
    $("#personalPhone").replaceWith("<input class=\"form-control\" type=\"\" id=\"personalPhone\">");
    $("#personalEmail").replaceWith("<input class=\"form-control\" type=\"email\" id=\"personalEmail\">");
}